package priv.tuyou.system.interceptor;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import priv.tuyou.bo.Page;
import priv.tuyou.bo.SqlParamGroup;
import priv.tuyou.bo.SqlParam.Condition;
import priv.tuyou.constants.WebConstants;
import priv.tuyou.constants.WebContext;
import priv.tuyou.dao.IDao;
import priv.tuyou.system.dao.ISystemMenuDao;
import priv.tuyou.system.po.SystemMenu;
import priv.tuyou.system.service.ISystemMenuService;
import priv.tuyou.util.UrlUtil;

/**
 * 提取各种参数的拦截器
 * @author：涂有
 * @date 2017年1月2日 下午4:34:31
 */
public class ParamInterceptor extends HandlerInterceptorAdapter{

	@Resource
	private IDao dao;
	@Resource
	private ISystemMenuDao systemMenuDao;
	@Resource
	private ISystemMenuService systemMenuService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		setPage(request);
		getRedirectUrl(request);
		setNavigation(request);
		return super.preHandle(request, response, handler);
	}
	
	/**
	 * 设置各种访问路径相关的参数
	 * @author：涂有
	 * @date 2017年1月2日 下午4:35:51
	 * @param request
	 * @return
	 */
	public void getRedirectUrl(HttpServletRequest request){
		
		String url = request.getRequestURI(); //uri不带协议名、域名，url反之
		request.setAttribute(WebConstants.URI, url);
		
		int index =  url.lastIndexOf('/');
		request.setAttribute(WebConstants.PATH, url.substring(0, index));
		request.setAttribute(WebConstants.ACTION_NAME, url.substring(index));
		
		if(url.contains("/login.action")){
			
			url = "/index.action";
		}else{
			
			//加入随机数
			url += "?random=" + RandomUtils.nextInt();
			Map<String, String> map = UrlUtil.getMap(request);
			map.remove("random");
			url += UrlUtil.mapToString(map, '&');
		}
		request.setAttribute(WebConstants.ALL_URI, url);
	}
	
	/**
	 * 设置分页的start和pageSize参数
	 * @author：涂有
	 * @date 2017年1月2日 下午4:37:26
	 * @param request
	 */
	public void setPage(HttpServletRequest request){
		
		String pageStart = request.getParameter("pager.offset");
		long start = NumberUtils.toLong(pageStart);

		@SuppressWarnings("rawtypes")
		Page<?> page = new Page(start, 3);
		WebContext.setPage(page);
	}
	
	/**
	 * 设置导航信息
	 * @author：涂有
	 * @date 2017年1月2日 下午10:18:38
	 */
	public void setNavigation(HttpServletRequest request){
		
		String uri = (String)request.getAttribute(WebConstants.URI);
		List<SystemMenu> menus = dao.queryIgnoreDeleted(SystemMenu.class, new SqlParamGroup("url", Condition.eq, uri));
		if(menus.size() == 1){
			
			request.setAttribute(WebConstants.NAVIGATION, systemMenuService.getPath(menus.get(0)));
		}
	}
}
